;(function(undefined) {
    "use strict"
    var _global;

    function result(args,fn){
        var argsArr = Array.prototype.slice.call(args);
        if(argsArr.length > 0){
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }
    var roleList = {
        columnsInit:function(){
            return  [
	            {
	            	title: '序号',
	                field: 'id',
	                width:'2%',
	                align:'center',
	                valign: 'middle',
	                formatter: function (value, row, index) {
	                    return index + 1;
	                }
	            },
	            {
	            	title: '角色名称',
	                field: 'roleName',
	                valign: 'middle',
	                sortable : true
	                
	            },
	            {
	            	title: '角色编码',
	                field: 'roleCode',
	                valign: 'middle',
	                sortable : true
	            },
	            {
	                field: 'rowSort',
	                valign: 'middle',
	                title: '排序号',
	                sortable : true
	            },
	            {
	                field: 'remarks',
	                valign: 'middle',
	                title: '备注'
	            },
	            {
	                checkbox: true
	            },
	            {
	                field: 'option',
	                title: '操作',
	                width: 100,
	                align: 'center',
	                formatter: function (value, row, index) {
	                    //up菜单向上展示、 down向下展示
	                    var pageSize = roleList.pageSize;
	                    var cssStyle = 'bottom';
	                    if (index > pageSize / 3) {
	                        cssStyle = 'top';
	                    }
	                    return [
	                        '<div class="opt-dropdown"><a class="tb-opt-icon" href="javascript:void(0)">操作 <i class="glyphicon glyphicon-triangle-bottom"></i></a>',
	                        '<ul class="opt-dropdown-menu opt-dropdown-menu-bottom">',
	                        '<li><a href="javascript:void(0)" onclick="updateRole(\''+row.id+'\');" title="编辑">',
	                        '<i class="glyphicon glyphicon-pencil"></i> 编辑</a></li>',
	                        '<li><a href="javascript:void(0)" onclick="settingRoleUser(\''+row.roleName+'\',\''+row.roleCode+'\');"><i class="glyphicon glyphicon-cog"></i> 设置用户</a></li></ul></div>'
	                    ].join('');
	                }
	            }
            ]
        },
        gridInit:function(columns){
            return $("#roleTable").bootstrapTable({
            	method: "post",
                contentType: "application/x-www-form-urlencoded",
                url:$$.restServerUrl + '/bootstrap/basegrid/BaseRoleBusiness/list',
                columns: columns,
                undefinedText: '-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                pagination: 'true',
                clickToSelect: true,
                singleSelect: false,
                sidePagination: "server",
                queryParamsType: "page",
                sortSide: 'client',
                sortable: true,
                pageNumber: 1,
                pageSize: 10,
                idField: 'id',
                silentSort: true,
                pageList: [
                    10, 20, 50, 100
                ],
                queryParams: function queryParams(params) {//设置查询参数
                    var args = {};
                    var roleName = $("#roleName").val();
                    var roleCode = $("#roleCode").val();
                    if(roleName!==""){
                    	args.c_roleName_7 = roleName;
                    }
                    if(roleCode!==""){
                    	args.c_roleCode_7 = roleCode;
                    }
                    args.page = params.pageNumber - 1;//params.pageNumber
                    args.pageSize = params.pageSize;//params.pageSize
                    args.isPage = 1;
                    var paramStr = JSON.stringify(args);
                    var param = {
                        params: paramStr
                    };
                    return param;
                },
                onPostBody:function () {
                    $(".opt-dropdown").hover(function(){
                        $(this).find(".opt-dropdown-menu").show();
                    },function(){
                        $(this).find(".opt-dropdown-menu").hide();
                    })
                }
            });
        },
        refresh: function () {
            $("#roleTable").bootstrapTable('refresh');
        }
    }

    // 将插件对象暴露给全局对象
    _global = (function(){ return this || (0, eval)('this'); }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = roleList;
    } else if (typeof define === "function" && define.amd) {
        define(function(){return roleList;});
    } else {
        !('plugin' in _global) && (_global.roleList = roleList);
    }
}());

/**
 * 新增角色
 */
function addRole() {
	openOperateWindow("role_add.html","add","");
}

/**
 * 修改角色
 */
function updateRole(id) {
    openOperateWindow("role_add.html","update",id);
}

/**
 * 打开操作窗口
 */
function openOperateWindow(url,type,id){
	var title = "";
	if(type=="add"){
		title = "新建角色";
	}else{
		title = "修改角色";
	}
	var openWin;
    layer.open({
        move: false,
        type: 2,
        title: title,
        area: ['800px', '350px'],
        content: url,
        btn: ['确定','关闭'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.initData(type,id);
        },
        yes: function (index, layero) {
            var validFormRes = openWin.submitForm();
            if(validFormRes){
            	layer.close(index);
            	layer.msg(title+"成功！",{time:1000});
            	roleList.refresh();
            }
        },
        cancel: function (index) {
            layer.close(index);
        }
    });
}

/**
 * 给角色分配用户
 */
function settingRoleUser(roleName,roleCode) {
   	var openWin;
   	var title = "角色分配用户-"+roleName+"("+roleCode+")";
    layer.open({
        move: false,
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: 'role_setting.html',
        btn: ['关闭'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.initData(roleCode);
        },
        yes: function (index, layero) {
        	layer.close(index);
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}

/**
 * 批量删除数据
 */
function batchDeleteData(){
	var len = $("#roleTable input:checked").length;
    if (len == 0) {
        layer.msg('请选择数据',{time:1000});
    } else {
        layer.confirm('确定要删除选中数据吗？',{icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {
        	var indexLoad = layer.load(2);
			var indexTips = layer.tips('正在努力删除数据，请等待...','#del-btn',{time:30*60*1000});
        	var rowDatas= $("#roleTable").bootstrapTable('getSelections');
        	var rowIds = [];
        	var roleCodes = [];
        	for (var i = 0; i < rowDatas.length; i++) {
            	rowIds.push(rowDatas[i].id);
            	roleCodes.push(rowDatas[i].roleCode);
        	}
        	layer.close(index);
        	$$.ajax({
            	url: "/rest/BaseRoleBusiness/remove",
            	data: {
                	id : rowIds.join(','),
                	roleCode : roleCodes.join(',')
            	},
            	success: function(data) {
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            		roleList.refresh();
            	},
            	serror : function(){
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            	},
            	error: function(){
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            	}
        	});
        });
    }
}

$(function () {
    $('#roleName').focus();
    
    //渲染表格
    var columns = roleList.columnsInit();
    var table = roleList.gridInit(columns);
    
    //重置表单
    $("#searchReset").on("click",function(){
        $('#roleName').val('');
        $('#roleCode').val('');
        roleList.refresh();
    });
    
    //按钮搜索
    $("#serachBtn").on("click",function(){
        roleList.refresh();
    });
    
    //回车搜索
    $('.entrer-query').bind('keypress',function(e){
        if(e.keyCode == 13){
            roleList.refresh();
        }
    });
    
    //点击删除按钮信息弹出框
    $("#del-btn").click(function(){
		batchDeleteData();
    });
})